package com.avanty.spbnetty.controller;

import com.avanty.spbnetty.dbconfig.TargetDataSource;
import com.avanty.spbnetty.pojo.Car;
import com.avanty.spbnetty.pojo.Vlt;
import com.avanty.spbnetty.service.CarServiceImpl;
import com.avanty.spbnetty.service.VltServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.transaction.Transactional;
import java.util.List;

@RestController
public class HelloController {

    @Autowired
    CarServiceImpl carServiceImpl;

    @Autowired
    VltServiceImpl vltServiceImpl;

    @RequestMapping("/addCar")
    public String addCar() {
        Car car = new Car();
        car.setCarBrand("BMW");
        car.setCarNum("浙A1267N");
        carServiceImpl.addCar(car);
        return "Car SUCCESS";
    }

    @RequestMapping("/findCar")
    public Car findByBrand(String brand) {
        return carServiceImpl.findByBrand(brand);
    }

    @RequestMapping("/findAll")
    public List selectAll() {
        return carServiceImpl.selectAll();
    }

    /**
     * @URL http://127.0.0.1:9090/addValue?value=first
     */
    @RequestMapping("/addValue")
    @TargetDataSource("slave")
    public String addValue(@RequestParam(value = "value", required = false) String value) {
        Vlt vlt = new Vlt();
        vlt.setMvalue(value);
        vltServiceImpl.addVlt(vlt);
        return "Vlt SUCCESS";
    }

    /**
     * @URL http://127.0.0.1:9090/addVlt?mvalue=second
     */
    @RequestMapping("/addVlt")
    @TargetDataSource("slave")
    public String addValue(Vlt vlt) {
        vltServiceImpl.addVlt(vlt);
        return "Vlt SUCCESS";
    }

    @RequestMapping("/Transactional")
    @TargetDataSource("slave")
    @Transactional(rollbackOn = {Exception.class})
    public String TransactionalTest() {
        try {
            Vlt vlt1 = new Vlt();
            vlt1.setMvalue("t5");
            vltServiceImpl.addVlt(vlt1);
            vlt1 = null;
            vlt1.getMvalue();
            Vlt vlt2 = new Vlt();
            vlt2.setMvalue("t6");
            vltServiceImpl.addVlt(vlt2);
            return "Transactional SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
